<?php

namespace App\Http\Controllers\Admins\Admin;

use App\Http\Controllers\Admins\BaseAdminController;
use App\Models\Admins;
use App\Models\OperationalLogs;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\View\Factory;
use Illuminate\Contracts\View\View;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Tymon\JWTAuth\Facades\JWTAuth;

class AdminController extends BaseAdminController
{
    /**
     * 激活账号
     *
     * @param Request $request
     * @return array
     */
    public function activateAccount(Request $request): array
    {
        $admin_id = $request->get('admin_id');
        $activation_code = $request->get('activation_code');
        if(!$activation_code){
            return retError([
                'msg'=>'请输入激活码'
            ]);
        }
        $where = [
            'id'=>$admin_id,
        ];
        $admin_code = Admins::query()->where($where)->value('activation_code');
        if($admin_code != $activation_code){
            return retError([
                'msg'=>'无效的激活码'
            ]);
        }
        $logs = [
            'admin_id'=>$admin_id,
            'operate_menu'=>OperationalLogs::$operateItem['login'],
            'operate_item'=>'激活账号',
            'operate_content'=>'登录-激活账号',
        ];
        DB::beginTransaction();
        try{
            #todo:有效期暂定激活账号日期基础上增加一年
            Admins::query()->where($where)->update([
                'is_activation'=>'1',
                'expired_at'=>  Carbon::now()->addYear()->toDateTimeString()
            ]);
            #日志
            OperationalLogs::AddOperationalLogs($logs);
            DB::commit();
            return ret([
                'data'=>'账号已激活'
            ]);
        }Catch(\Exception $exception){
            DB::rollback();
            return retError([
                'msg'=>$exception->getMessage()
            ]);
        }
    }

    public function index(Request $request){
        $condition = $request->get('condition','username');
        if($request->isMethod('post')){
            # 要执行的代码
            $query = Admins::query()->latest();
            $keywords = $request->get('keywords',null);
            if ($keywords) {
                $query->where($condition, 'like', '%' . $keywords . '%');
            }
            $status = $request->get('status','all');
            if($status != 'all'){
                $query->where('status', $status);
            }
            $pageSize = $request->get('limit',10);
            # 计算offset值
            $offset = $request->get('offset',0);
            # 总数
            $total = $query->count();
            $data = $query->limit($pageSize)->offset($offset)->get();
            $result = array();
            if($data){
                foreach($data as $val){
                    $status_show =  getStatusValue($val['status']);
                    $result[] = [
                        'id'=>$val['id'],
                        'name'=>$val['name'],
                        'username'=>$val['username'],
                        'phone'=>$val['phone'],
//                        'posts_name'=>$posts_name,
//                        'department_name'=>$department_name,
                        'status'=>$val['status'],
                        'roles'=>$val['roles'],
                        'status_show'=>$status_show,
//                        'admin_name'=>Admins::query()->where('id',$val['add_admin_id'])->value('username')?:'-',
                        'crated_at'=>Carbon::parse($val['crated_at'])->toDateTimeString(),
                    ];
                }
            }
            return ret([
                'total'=>$total,
                'data'=>$result
            ]);
        }
        $admin_id = $request->get('admin_id');
        $subtitle = '管理员账号';
        $compact = compact('subtitle','admin_id');
        return view('v1.admin.admin.index',$compact);
    }

    /**
     * 添加账号
     *
     * @param Request $request
     * @return Application|Factory|View|RedirectResponse
     */
    public function add(Request $request)
    {
        if($request->isMethod('post')) {
            $admin_id = $request->get('admin_id');
            $table = 'account';
            #表单验证
            $validator = AdminFormVerify($table, $request);
            if ($validator->fails()) {
                return $this->retError($validator,$request);
            }
            $post = $request->all();
            $vp = VerifyMobile($post['phone'],true);
            if($vp['code'] == 0){
                return $this->retError($vp['msg_zh'],$request);
            }
            $username = $request->get('username');
//            $posts_id = implode(',',$post['posts_id']);
            unset($post['_token']);
            unset($post['posts_id']);
            $create = $post;
//            $create['posts_id'] = $posts_id;
//            $create['add_admin_id'] = $admin_id;
//            $create['activation_code'] = ActivationCode();
            $create['password'] = bcrypt($post['password']);
            $logs = [
                'admin_id' => $admin_id,
                'operate_menu' => OperationalLogs::$operateItem['account_manage'],
                'operate_item' => $username,
                'operate_content' => '添加管理员账号：' . $username,
            ];
            DB::beginTransaction();
            try {
                Admins::query()->create($create);
                #操作日志
                OperationalLogs::AddOperationalLogs($logs);
                DB::commit();
                return $this->retSuccess();
            } catch (\Exception $exception) {
                DB::rollback();
                return $this->retError($exception->getMessage(),$request);
            }
        }
        $url = route('v1.account.index');
        $params = [
            'url'=>$url,
            'success'=>'success'
        ];
        $subtitle = '新增账号';
        $view = 'v1.admin.admin.add';
        $compact = compact('subtitle','params');
        return view($view,$compact);
    }

    /**
     * 编辑账号
     *
     * @param Request $request
     * @param $id
     * @return Application|Factory|View|RedirectResponse
     */
    public function edit(Request $request,$id)
    {
        $model = Admins::query();
        $where = [
            'id'=>$id
        ];
        $model_query = AdminModelQuery($id,$model,$where);
        if($model_query['code'] == 0){
            return  $this->retError($model_query['msg'],$request);
        }
        if($request->isMethod('post')) {
            $admin_id = $request->get('admin_id');
            $table = 'account';
            #表单验证
            $validator = AdminFormVerify($table, $request,'update');
            if ($validator->fails()) {
                return $this->retError($validator,$request);
            }
            $post = $request->all();
            $vp = VerifyMobile($post['phone'],true);
            if($vp['code'] == 0){
                return $this->retError($vp['msg_zh'],$request);
            }
            $username = $request->get('username');
            $where_unique_username = [
                'username'=>$username,
            ];
            $Model = Admins::query();
            $data_unique = AdminUpdateDataUniqueVerify($Model,$id,$where_unique_username);
            if($data_unique['code'] == 201){
                return $this->retError($data_unique['msg'],$request);
            }
            $where_unique_phone = [
                'phone'=>$post['phone'],
            ];
            $Model1 = Admins::query();
            $data_unique1 = AdminUpdateDataUniqueVerify($Model1,$id,$where_unique_phone);
            if($data_unique1['code'] == 201){
                return $this->retError($data_unique1['msg'],$request);
            }
//            $posts_id = implode(',',$post['posts_id']);
            $password = $post['password'];
            unset($post['_token']);
            unset($post['password']);
            $update = $post;
            if($password){
                $update['password'] = bcrypt($password);
            }
//            $update['posts_id'] = $posts_id;
//            $update['add_admin_id'] = $admin_id;
            $logs = [
                'admin_id' => $admin_id,
                'operate_menu' => OperationalLogs::$operateItem['account_manage'],
                'operate_item' => $username,
                'operate_content' => '修改管理员账号：' . $username,
            ];
            DB::beginTransaction();
            try {
                Admins::query()->where('id',$id)->update($update);
                #操作日志
                OperationalLogs::AddOperationalLogs($logs);
                DB::commit();
                return $this->retSuccess();
            } catch (\Exception $exception) {
                DB::rollback();
                return $this->retError($exception->getMessage(),$request);
            }
        }
        $url = route('v1.account.index');
        $params = [
            'url'=>$url,
            'success'=>'success'
        ];
        $subtitle = '修改管理员账号';
        $view = 'v1.admin.admin.edit';
//        $columns = ['id','username','name','phone'];
        $data = Admins::query()->find($id);
        $data['avatar_show'] = '';
        if($data['avatar']){
            $data['avatar_show'] = env('APP_URL').Storage::url($data['avatar']);
        }
//        dd($data->toArray());
        $compact = compact('subtitle','params','data');
        return view($view,$compact);
    }

    /**
     * 修改账号状态
     *
     * @param $id
     * @return void
     */
    public function changeStatus($id){
        $model = Admins::query();
        $where = [
            'id'=>$id
        ];
        $model_query = AdminModelQuery($id,$model,$where);
    }

    /**
     * 删除账号
     *
     * @param Request $request
     * @param $id
     * @return array
     * @throws \Throwable
     */
    public function delete(Request $request,$id): array
    {
        $model = Admins::query();
        $where = [
            'id'=>$id
        ];
        $model_query = AdminModelQuery($id,$model,$where);
        if($model_query['code'] == 0){
            return AdminRetError($model_query['msg']);
        }
        $data = $model->where($where);
        $logs = [
            'admin_id'=>$request->get('admin_id'),
            'operate_menu'=>OperationalLogs::$operateItem['account_manage'],
            'operate_item'=>Admins::query()->where($where)->value('username').'('.$id.')',
            'operate_content'=>OperationalLogs::$operate['account_delete'],
        ];
        return AdminDeleteData($data,$logs);
    }
}
